#-*- coding:UTF-8 -*-

import contextlib
import traceback

import sqlalchemy
import sqlalchemy.orm

from ..config import get_property
from ..logger import logger


dbecho=get_property('db.echo').lower()=='true' and True or False


engine=sqlalchemy.create_engine('mysql://%s:%s@%s/%s?charset=%s'%(get_property('db.user'),\
            get_property('db.pass'),get_property('db.host'),\
            get_property('db.db'),get_property('db.charset')),\
            pool_recycle=28800,\
            echo=dbecho)


def _get_DB_session():
    DBSession=sqlalchemy.orm.sessionmaker(bind=engine)
    return DBSession()


@contextlib.contextmanager
def session_context():
    try:
        session=_get_DB_session()
        yield session
    except Exception as be:
        logger.debug('session_context exception : %s'%be)
        traceback.print_exc()
    finally:
        #logger.debug('session_context close session')
        if session is not None:
            session.close()


class SessionContext(object):
    def __init__(self):
        self._need_commit=False
        self._session=None

    def __enter__(self):
        try:
            self._session=_get_DB_session()
        except Exception as ex:
            logger.debug('SessionContext.__enter__ exception: %s'%ex)
            traceback.print_exc()
        return self._session

    def __exit__(self, exec_type, exec_value, exec_traceback):
        try:
            if self._session:
                if self._need_commit:
                    self._session.commit()
                self._session.close()
        except Exception as ex:
            logger.debug('SessionContext Exception : %s'%ex)
            traceback.print_exc()


class SessionHolder(object):
    def __init__(self):
        self._need_commit=False
        self._session=None

    def __enter__(self):
        try:
            self._session=_get_DB_session()
        except Exception as ex:
            logger.debug('SessionContext __enter__ exception: %s'%ex)
            traceback.print_exc()
        return self

    def get_session(self):
        return self._session

    def set_commit(self, value):
        self._need_commit=value

    def __exit__(self, exec_type, exec_value, exec_traceback):
        try:
            if self._session:
                if self._need_commit:
                    self._session.commit()
                self._session.close()
        except Exception as ex:
            logger.debug('SessionContext __exit__ Exception : %s'%ex)
            traceback.print_exc()
